<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <br />
    <br />

    <span>
      搜索：
      <el-input style="width:15rem" placeholder="用户名" @input="search" v-model="search_name"></el-input>
    </span>
    <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>

    <el-divider></el-divider>
    <el-table
      :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
      style="width: 100%"
      class="table"
      @selection-change="handleSelectionChange"
      height="550"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="昵称"></el-table-column>
      <el-table-column prop="role_id" label="角色"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="电子邮箱"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="warning" size="mini" icon="el-icon-user" @click="permissions(scope.row)"></el-button>
          <el-button type="success" size="mini" icon="el-icon-edit" @click="edit(scope.row)"></el-button>
          <el-button type="primary" size="mini" icon="el-icon-delete" @click="remove(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[9,12,tableData.length]"
      :page-size="pagesize"
      layout="total,sizes,prev,pager,next,jumper"
      :total="tableData.length"
    ></el-pagination>
    <br />
    <el-button size="medium" type="primary" icon="el-icon-delete" @click="removeMore">批量删除</el-button>
    <el-drawer title="drawer" :visible.sync="drawer" size="35%" :with-header="false">
      <div class="form-div">
        <h3>用户信息</h3>
        <el-form :model="userForm" ref="userForm" label-width="130px" class="add-user-form">
          <el-form-item
            label="用户名"
            prop="username"
            :rules="[{ required: true, message: '请输入用户名'}]"
          >
            <el-input style="width:20rem" v-model="userForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <br />
          <el-form-item
            label="昵称"
            prop="name"
            :rules="[{ required: true, message: '请输入昵称'}]"
          >
            <el-input style="width:20rem" v-model="userForm.name" autocomplete="off"></el-input>
          </el-form-item>
          <br />
          <el-form-item
            label="密码"
            prop="password"
            :rules="[{ required: true, message: '请输入密码'}]"
          >
            <el-input
              style="width:20rem"
              v-model="userForm.password"
              autocomplete="off"
              show-password
            ></el-input>
          </el-form-item>
          <br />
          <el-form-item
            label="手机号"
            prop="phone"
            :rules="[{ required: true, message: '请输入手机号'}]"
          >
            <el-input style="width:20rem" v-model="userForm.phone" autocomplete="off"></el-input>
          </el-form-item>
          <br />
          <el-form-item
            label="电子邮箱"
            prop="email"
            :rules="[{ required: true, message: '请输入电子邮箱'}]"
          >
            <el-input style="width:20rem" v-model="userForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            class="radio"
            label="角色"
            prop="role_id"
            :rules="[{ required: true, message: '请选择用户角色'}]"
          >
            <el-radio v-model="userForm.role_id" label="MVO">销售商</el-radio>
            <el-radio v-model="userForm.role_id" label="BVO">借卖商</el-radio>
          </el-form-item>

          <el-form-item class="user-form-button">
            <el-button type="primary" @click="submitForm('userForm')">提交</el-button>
            <el-button @click="cancel('userForm')">取消</el-button>
          </el-form-item>
          <br />
        </el-form>
      </div>
    </el-drawer>
    <!-- direction="ltr" -->
    <el-drawer title="drawer" :visible.sync="drawerPr" size="20%" :with-header="false">
      <div class="form-div">
        <h3>授予用户权限</h3>
        <span>管理员：</span>
        <div class="switch" v-for="item in menu0" :key="item.menu_id">
          <el-switch v-model="item.state" active-color="#13ce66" inactive-color="#D8D8D8" @change="changePermission($event,item.menu_id)"></el-switch>
          <p class="p-menu">
            <i :class="item.menu_icon"></i>
            {{item.menu_name}}
          </p>
        </div>
        <span>销售商：</span>
        <div class="switch" v-for="item in menu1" :key="item.menu_id">
          <el-switch v-model="item.state" active-color="#13ce66" inactive-color="#D8D8D8" @change="changePermission($event,item.menu_id)"></el-switch>
          <p class="p-menu">
            <i :class="item.menu_icon"></i>
            {{item.menu_name}}
          </p>
        </div>
        <span>借卖商：</span>
        <div class="switch" v-for="item in menu2" :key="item.menu_id">
          <el-switch v-model="item.state" active-color="#13ce66" inactive-color="#D8D8D8" @change="changePermission($event,item.menu_id)"></el-switch>
          <p class="p-menu">
            <i :class="item.menu_icon"></i>
            {{item.menu_name}}
          </p>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1, //默认页码为1
      pagesize: 9, //默认一页显示11条
      menu0: [],
      menu1: [],
      menu2: [],
      beingChangedUserID:0,
      search_name: "",
      drawerPr: false,
      drawer: false,
      isAdd: false,
      tableData: [],
      table: [],
      multipleSelection: [],
      userForm: {
        user_id: "",
        username: "",
        name: "",
        password: "",
        phone: "",
        email: "",
        role_id: ""
      }
    };
  },
  mounted() {
    this.$post("/wal/getroleid", {
      user_id: sessionStorage.getItem("user_id")
    }).then(res => {
      if (res.message == "0") {
        this.getUsers();
      } else {
        this.$message.warning("权限被拒");
      }
    });
  },
  methods: {
    handleSizeChange(size) {
      //一页显示多少条
      this.pagesize = size;
    },
    handleCurrentChange(currentPage) {
      //页码更改方法
      this.currentPage = currentPage;
    },
    getUsers() {
      this.$post("/rle/getUsers", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.user;
          this.table = res.data.user;
        } else {
          if (res.message == "Permission denied") {
            this.$message.warning("权限被拒");
          }
        }
      });
    },
    permissions(row) {    //权限管理获取状态列表
      if(row.user_id == 3){
        this.$message.warning("无法编辑管理员帐户");
        return
      }
      this.$post("/menuList/getAllMenusWithState", {
        user_id: row.user_id
      }).then(res => {
        if (res.code == 504) {
          this.$message.warning(res.message);
          return;
        }
        if (res.code == 200) {
          this.menu0 = res.data.filter(e => e.parent_id == 0);
          this.menu1 = res.data.filter(e => e.parent_id == 1);
          this.menu2 = res.data.filter(e => e.parent_id == 2);
          this.beingChangedUserID = row.user_id;
        }
      });

      this.drawerPr = true;
    },
    changePermission(state,menu_id){  //权限改变回调函数
      if(this.beingChangedUserID==0){
        this.$message.warning("您更改了错误的用户，请再次确认。");
      }
      if(state == true){
        this.$post("/menuList/addMenuList", {
        user_id: this.beingChangedUserID,
        menu_id: menu_id
      }).then(res => {
        if (res.code == 504) {
          this.$message.warning("权限修改失败，请重试");
          this.drawerPr = false;
          return;
        }
        if (res.code == 200) {
          this.$message.success("当前用户权限升级成功！");
        }
      });
      }
      if(state == false){
        this.$post("/menuList/deleteMenuList", {
        user_id: this.beingChangedUserID,
        menu_id: menu_id
      }).then(res => {
        if (res.code == 504) {
          this.$message.warning("权限修改失败，请重试\n" +
              "\n");
          this.drawerPr = false;
          return;
        }
        if (res.code == 200) {
          this.$message.success("当前用户权限降级成功！");
        }
      });
      }
      console.log(state);
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            let tmp;
            if(this.userForm.role_id=="Admin"){
              tmp = "0"
              return;
            }
            if(this.userForm.role_id=="MVO"){
              tmp = "1";
            }
            if(this.userForm.role_id=="BVO"){
              tmp = "2";
            }
            this.$post("/user/register", {
            username: this.userForm.username,
            password:this.userForm.password,
            name:this.userForm.name,
            phone:this.userForm.phone,
            email:this.userForm.email,
            role_id:tmp
          }).then(res => {
            if (res.code == 504) {
              this.$notify.error("此用户名已存在");
            }
            if (res.code == 200) {
              this.getUsers();
              this.$notify.success("注册成功");
            }
          });
            this.isAdd = false;
          } else {
            this.$post("/rle/updateUser", {
              admin_id: sessionStorage.getItem("user_id"),
              user_id: this.userForm.user_id,
              username: this.userForm.username,
              password: this.userForm.password,
              name: this.userForm.name,
              email: this.userForm.email,
              phone: this.userForm.phone,
              role_id: this.userForm.role_id
            }).then(res => {
              if (res.code == 200) {
                this.getUsers();
                this.$message.success("修改成功！");
              } else {
                this.$message.warning("修改失败");
              }
            });
          }
          this.drawer = false;
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.$refs[formName].resetFields();
      this.drawer = false;
    },
    add() {
      this.isAdd = true;
      this.userForm = [];
      this.drawer = true;
    },
    edit(row) {
      this.isAdd = false;
      this.userForm = JSON.parse(JSON.stringify(row));
      console.log(row);
      if (this.userForm.role_id == "Admin") {
        this.$message.warning("无法编辑管理员账户");
        return;
      }
      this.drawer = true;
    },
    remove(row) {
       if (this.userForm.role == "Admin") {
        this.$message.warning("不能移除管理员账户");
        return;
      }
      this.$post("/rle/deletedUser", {
        user_id: sessionStorage.getItem("user_id"),
        delete_id: row.user_id
      }).then(res => {
        if (res.code == 200) {
          this.getUsers();
          this.$message.success("删除成功");
        } else {
          this.$message.warning("删除失败");
        }
      });
      
    },
    removeMore() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请选择需要操作的信息");
        return;
      }
      this.multipleSelection.forEach(element => {
        this.$post("/rle/deletedUser", {
          user_id: sessionStorage.getItem("user_id"),
          delete_id: element.user_id
        }).then(res => {
          if (res.code == 200) {
            this.getUsers();
          } else {
            this.$message.warning("删除失败");
          }
        });
      });

      this.$message.success("删除成功");
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    search() {
      this.tableData = this.table.filter(e =>
        e.username.match(this.search_name)
      );
    }
  }
};
</script>

<style scoped>
.p-menu {
  margin-left: 1rem;
}
.switch {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.form-div {
  margin-left: 3rem;
  height: 50rem;
}
.add-user-form {
  margin-top: 5rem;
}
.user-form-button {
  margin-top: 3rem;
  margin-left: 10rem;
}
.table >>> .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #1598ec;
  border-color: #1598ec;
}
.table >>> .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #1598ec;
  border-color: #1598ec;
}
.table >>> .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #1598ec;
}
.radio >>> .el-radio__input.is-checked .el-radio__inner {
  border-color: #1598ec;
  background: #1598ec;
}
.radio >>> .el-radio__input.is-checked + .el-radio__label {
  color: #1598ec;
}
</style>